//
//  YSLHomeViewController.m
//  used
//
//  Created by lanou on 16/7/13.
//  Copyright © 2016年 王凯. All rights reserved.
//

#import "YSLHomeViewController.h"

@interface YSLHomeViewController ()<UITableViewDataSource,UITableViewDelegate, YSLRecommendCellDelegate,UISearchBarDelegate>
/** 轮播图的图片 */
@property (nonatomic, strong) NSMutableArray *scrollArray;

/** 数据源 */
@property (nonatomic, strong) NSMutableArray *dataSource;

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, assign)NSInteger page; //页数

/** 请求参数 */
@property (nonatomic, strong) NSMutableDictionary *params;

@property (nonatomic, strong)UIView *basisView; //底板 View

@property (nonatomic, strong)NSMutableArray *imageArray;

@property (nonatomic, strong)YSLRecommendCell *recommendCell; //自定义cell

@property (strong, nonatomic) FeHourGlass *hourGlass;

@end

@implementation YSLHomeViewController

- (UIView *)basisView {

    if (!_basisView) {
        _basisView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight * 0.55 + 25)];
        
        _basisView.backgroundColor = KLRGBColor(220, 220, 220);
    }
    return _basisView;
}

- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (NSMutableArray *)scrollArray{
    if (!_scrollArray) {
        _scrollArray = [NSMutableArray array];
    }
    return _scrollArray;
}

- (NSMutableArray *)imageArray{
    if (!_imageArray) {
        _imageArray = [NSMutableArray array];
    }
    return _imageArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    //设置导航栏标题
    self.navigationItem.titleView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationTitleImage"]];
    
    self.tableView.backgroundColor = KLRGBColor(220, 220, 220);
    [self.tableView registerNib:[UINib nibWithNibName:@"YSLRecommendCell" bundle:nil] forCellReuseIdentifier:@"YSLRecommendModel_cell"];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImage:@"home_category_icon" highImage:nil target:self action:@selector(rightAction)];
    //二维码
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.extendedLayoutIncludesOpaqueBars = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self setNeedsStatusBarAppearanceUpdate];
    
    //加载数据
    [self loadData];
    
    //专题
    [self loadSpecial];
    
    //刷新
    [self setupRefresh];

   self.hourGlass = [[FeHourGlass alloc] initWithView:self.view];
    [self.view addSubview:self.hourGlass];
    [self.hourGlass show];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self.hourGlass dismiss];
}

#pragma mark - 加载数据
- (void)loadData
{

    [self.tableView addSubview:self.basisView];

    [RequestManager fetchDataWithUrl:KHomeRecommendUrl parameter:@{@"page": @0} method:@"POST" compeleted:^(NSData *data) {
        NSDictionary *bigDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        //添加轮播图的数据源
        for (NSDictionary *smallDic in bigDic[@"result"][@"carousel"]) {
            [self.scrollArray addObject:smallDic[@"imageurl"]];
        }
        
        //tableView
        for (NSDictionary *dic in bigDic[@"result"][@"item"][@"list"]) {
            
            KLGood *model = [[KLGood alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.dataSource addObject:model];
        }
   
    } updateUI:^{
        
        //创建轮播图
        XSJScrollView *scrollView = [[XSJScrollView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight * 0.3) imageArray:self.scrollArray];
        [self.basisView addSubview:scrollView];
        self.tableView.tableHeaderView = self.basisView;
        
        //轻拍手势
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapScrollViewAction:)];
        //设置双击触发 设置点击次数
        tap.numberOfTapsRequired = 1;
        //设置手指数
        tap.numberOfTouchesRequired = 1;
        //给图片添加手势
        [scrollView addGestureRecognizer:tap];
        
        //打开图片的手势交互
        // 系统中的标签label和图片视图UIImageView默认是关闭交互的
        scrollView.userInteractionEnabled = YES;
        
        
        [UIView animateWithDuration:1.0 animations:^{
            
            self.hourGlass.alpha = 0;
        }];
        
        [self.tableView reloadData];

    }];
}

#pragma mark - 专题special
- (void)loadSpecial
{
    //专题图片
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, kHeight * 0.3 + 1, kWidth, kHeight * 0.25)];
    [self.basisView addSubview:imageView];
    //数据请求
    [RequestManager fetchDataWithUrl:@"http://api.91sph.com/specialTopic/advList" parameter:@{@"typeId":@0,@"pageIndex":@1} method:@"POST" compeleted:^(NSData *data) {
        NSDictionary *bigDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];

        //添加轮播图的数据源
        for (NSDictionary *smallDic in bigDic[@"data"][@"advList"][@"result"]) {
            [self.imageArray addObject:smallDic[@"picUrl"]];

        }
    } updateUI:^{
        
        //随机
        [imageView sd_setImageWithURL:[NSURL URLWithString:self.imageArray[arc4random()%self.imageArray.count]]];
    }];

    //轻拍手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapImageViewAction:)];
    //设置双击触发 设置点击次数
    tap.numberOfTapsRequired = 1;
    //设置手指数
    tap.numberOfTouchesRequired = 1;
    //给图片添加手势
    [imageView addGestureRecognizer:tap];
    
    //打开图片的手势交互
    // 系统中的标签label和图片视图UIImageView默认是关闭交互的
    imageView.userInteractionEnabled = YES;
 
    //每日推荐
    UILabel *specialLabel = [[UILabel alloc] initWithFrame:CGRectMake(kWidth/2 - 50, CGRectGetMaxY(imageView.frame) + 5, 100, 20)];
    specialLabel.text = @"每日推荐";
    specialLabel.textColor = [UIColor grayColor];
    specialLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:12];
    specialLabel.textAlignment = NSTextAlignmentCenter;
    
    //分割线
    UIImageView *lineLeft = [[UIImageView alloc] initWithFrame:CGRectMake(kWidth/6, specialLabel.frame.origin.y + 10, kWidth/4, 1)];
    lineLeft.image = [UIImage imageNamed:@"login_register_left_line"];

    [self.basisView addSubview:lineLeft];
  
    UIImageView *lineRight = [[UIImageView alloc] initWithFrame:CGRectMake(kWidth-specialLabel.frame.origin.x-20, specialLabel.frame.origin.y + 10, kWidth/4, 1)];
    lineRight.image = [UIImage imageNamed:@"login_register_right_line"];

    [self.basisView addSubview:lineRight];
    [self.basisView addSubview:specialLabel];
}


#pragma mark - 添加刷新控件
- (void)setupRefresh
{
    //添加下拉刷新
    self.tableView.mj_header = [MJRefreshStateHeader headerWithRefreshingBlock:^{
        //刷新之前清空数组
        [self.dataSource removeAllObjects];
        [self loadNewUsers];

    }];
    

    //添加上拉加载
    self.tableView.mj_footer = [MJRefreshBackGifFooter footerWithRefreshingBlock:^{

        [self loadMoreUsers];
    }];
}

#pragma mark - 刷新加载用户数据

//加载列表的数据 下拉
- (void)loadNewUsers
{
    [self.tableView.mj_footer endRefreshing];
    self.page = 0;

    //请求参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"page"] = @(self.page);
    self.params = params;
    
    [RequestManager fetchDataWithUrl:KHomeRecommendUrl parameter:params method:@"POST" compeleted:^(NSData *data) {
        NSDictionary *bigDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];

        //tableView
        for (NSDictionary *dic in bigDic[@"result"][@"item"][@"list"]) {
            
            KLGood *model = [[KLGood alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.dataSource addObject:model];
        }

    } updateUI:^{
        //结束刷新
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
      
        [self.tableView reloadData];
    }];
}

//加载用户数据 上拉
- (void)loadMoreUsers
{
    [self.tableView.mj_header endRefreshing];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"page"] = @(++self.page);
    self.params = params; //self.params存储的是最后一次请求
    
    [RequestManager fetchDataWithUrl:KHomeRecommendUrl parameter:params method:@"POST" compeleted:^(NSData *data) {
        NSDictionary *bigDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
       
        //tableView
        for (NSDictionary *dic in bigDic[@"result"][@"item"][@"list"]) {
            
            KLGood *model = [[KLGood alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.dataSource addObject:model];
        }

    } updateUI:^{
        //结束刷新
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        [self.tableView reloadData];
    }];
}

#pragma mark---tableViewDelegate----
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.dataSource.count == 0) {
        return 0;
    }
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    YSLRecommendCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YSLRecommendModel_cell" forIndexPath:indexPath];
    KLGood *model = self.dataSource[indexPath.row];
    cell.model = model;
    cell.sellerMessageButton.hidden = NO;
    cell.delegate = self;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 250;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    YSLCommodityViewController *commodityVC = [[YSLCommodityViewController alloc] init];
    KLGood *model = self.dataSource[indexPath.row];
    //model传值CommodityModel
    commodityVC.goodsID = model.ID;
    
    [self.navigationController pushViewController:commodityVC animated:YES];
}


#pragma mark ScrollView手势
- (void)tapScrollViewAction:(UITapGestureRecognizer *)tap {
    
    YSLScrollWebViewController *ScrollWebVC = [YSLScrollWebViewController new];
    [self.navigationController pushViewController:ScrollWebVC animated:YES];
}

#pragma mark - <YSLRecommendCellDelegate>

#pragma mark 专题手势
- (void)tapImageViewAction:(UITapGestureRecognizer *)tap {

    YSLSpecialViewController *specialVC = [YSLSpecialViewController new];
    [self.navigationController pushViewController:specialVC animated:YES];
    
}


#pragma mark - 扫码

- (void)rightAction {

    MyBarCodeController *ctrl = [[MyBarCodeController alloc] initWithNibName:@"MyBarCodeController" bundle:nil];
    ctrl.pageType = MyBarCodeControllerPageTypeScan;
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:ctrl];
    nav.title = @"扫一扫";
    [self presentViewController:nav animated:YES completion:nil];
    
}


#pragma mark - <YSLRecommendCellDelegate>

- (void)clickCollectionViewWithModelId:(NSNumber *)goodId {
    
    YSLCommodityViewController *commodityVC = [[YSLCommodityViewController alloc] init];
    
    commodityVC.goodsID = goodId;
    
    [self.navigationController pushViewController:commodityVC animated:YES];
}

- (void)clickButton:(UIButton *)button withModel:(KLGood *)model {
    
    if (button.tag == 1) {  // 点击用户头像
        KLSellerViewController *sellerVc = [[KLSellerViewController alloc] init];
        sellerVc.userID = model.userid;
        [self.navigationController pushViewController:sellerVc animated:YES];
    } else if (button.tag == 3) { // 点击地址
        KLBuyViewController *buyVc = [[KLBuyViewController alloc] init];
        NSMutableDictionary *para = [NSMutableDictionary dictionary];
        para[@"province"] = model.province;
        para[@"area"] = model.area;
        para[@"city"] = model.city;
        para[@"page"] = @0;
        buyVc.parameters = para;
        [self.navigationController pushViewController:buyVc animated:YES];
        
    } else if (button.tag == 4) { // 点击查看
        [self clickCollectionViewWithModelId:model.ID];
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{

    [self.view endEditing:YES];

}


@end
